<?php
/*
 * @Author: 波波
 * @Date: 2025-06-26 05:39:13
 * @Email: guqule2@yeah.net
 * @LastEditors: 波波
 * @LastEditTime: 2025-07-07 23:36:59
 * @Description: 丸子社区-专注分享交流的社区平台，连接你我
 * @Company: 丸子社区
 */


define('THEME_VERSION', '1.0.0');


require get_template_directory() . '/inc/codestar-framework/autoload.php';

require get_template_directory() . '/inc/theme-comments.php';
require get_template_directory() . '/inc/theme-login.php';
require get_template_directory() . '/inc/theme-common.php';
require get_template_directory() . '/inc/theme-single.php';
require get_template_directory() . '/inc/theme-ai.php';

// Added from system-messages plugin
function sm_register_post_type() {
    $labels = array(
        'name'                  => _x( '系统消息', 'Post type general name', 'wanzicms' ),
        'singular_name'         => _x( '系统消息', 'Post type singular name', 'wanzicms' ),
        'menu_name'             => _x( '系统消息', 'Admin Menu text', 'wanzicms' ),
        'name_admin_bar'        => _x( '系统消息', 'Add New on Toolbar', 'wanzicms' ),
        'add_new'               => __( '添加新消息', 'wanzicms' ),
        'add_new_item'          => __( '添加新系统消息', 'wanzicms' ),
        'new_item'              => __( '新系统消息', 'wanzicms' ),
        'edit_item'             => __( '编辑系统消息', 'wanzicms' ),
        'view_item'             => __( '查看系统消息', 'wanzicms' ),
        'all_items'             => __( '所有系统消息', 'wanzicms' ),
        'search_items'          => __( '搜索系统消息', 'wanzicms' ),
        'parent_item_colon'     => __( '父级系统消息:', 'wanzicms' ),
        'not_found'             => __( '未找到系统消息。', 'wanzicms' ),
        'not_found_in_trash'    => __( '回收站中未找到系统消息。', 'wanzicms' ),
        'featured_image'        => _x( '系统消息封面图片', 'Overrides the "Featured Image" phrase for this post type. Added in 4.3', 'wanzicms' ),
        'set_featured_image'    => _x( '设置封面图片', 'Overrides the "Set featured image" phrase for this post type. Added in 4.3', 'wanzicms' ),
        'remove_featured_image' => _x( '移除封面图片', 'Overrides the "Remove featured image" phrase for this post type. Added in 4.3', 'wanzicms' ),
        'use_featured_image'    => _x( '用作封面图片', 'Overrides the "Use as featured image" phrase for this post type. Added in 4.3', 'wanzicms' ),
        'archives'              => _x( '系统消息归档', 'The post type archive label used in nav menus. Default "Post Archives". Added in 4.4', 'wanzicms' ),
        'insert_into_item'      => _x( '插入到系统消息', 'Overrides the "Insert into post"/"Insert into page" phrase (used when inserting media into a post). Added in 4.4', 'wanzicms' ),
        'uploaded_to_this_item' => _x( '上传到此系统消息', 'Overrides the "Uploaded to this post"/"Uploaded to this page" phrase (used when viewing media attached to a post). Added in 4.4', 'wanzicms' ),
        'filter_items_list'     => _x( '筛选系统消息列表', 'Screen reader text for the filter links heading on the post type listing screen. Default "Filter posts list"/"Filter pages list". Added in 4.4', 'wanzicms' ),
        'items_list_navigation' => _x( '系统消息列表导航', 'Screen reader text for the pagination heading on the post type listing screen. Default "Posts list navigation"/"Pages list navigation". Added in 4.4', 'wanzicms' ),
        'items_list'            => _x( '系统消息列表', 'Screen reader text for the items list heading on the post type listing screen. Default "Posts list"/"Pages list". Added in 4.4', 'wanzicms' ),
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array( 'slug' => 'system-message' ),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => null,
        'supports'           => array( 'title', 'editor', 'author' ),
        'menu_icon'          => 'dashicons-info',
    );

    register_post_type( 'system_message', $args );
}
add_action( 'init', 'sm_register_post_type' );

function sm_display_system_message_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'id' => '',
    ), $atts, 'system_message' );

    $args = array(
        'post_type' => 'system_message',
        'posts_per_page' => 1,
        'orderby' => 'date',
        'order' => 'DESC',
    );

    if ( ! empty( $atts['id'] ) ) {
        $args['p'] = $atts['id'];
    }

    $message = new WP_Query( $args );

    if ( $message->have_posts() ) {
        while ( $message->have_posts() ) {
            $message->the_post();
            $output = '<div class="system-message">';
            $output .= '<h2 class="system-message-title">' . get_the_title() . '</h2>';
            $output .= '<div class="system-message-content">' . get_the_content() . '</div>';
            $output .= '</div>';
        }
        wp_reset_postdata();
        return $output;
    } else {
        return '';
    }
}
add_shortcode( 'system_message', 'sm_display_system_message_shortcode' );

function wz_enqueue_message_center_assets() {
    // Only load these assets on the message center page
    if ( is_page_template('page-message-center.php') ) {
        wp_enqueue_style(
            'system-messages-style',
            get_stylesheet_directory_uri() . '/system-messages.css',
            array(),
            '1.0',
            'all'
        );
        wp_enqueue_script(
            'message-center-js',
            get_template_directory_uri() . '/assets/js/message-center.js',
            array( 'jquery' ),
            '1.0',
            true
        );
    }
}
add_action( 'wp_enqueue_scripts', 'wz_enqueue_message_center_assets' );

/**
 * Enqueue subscription script and localize it.
 */
function wz_enqueue_subscription_script() {
    wp_enqueue_script( 'wz-subscription', get_template_directory_uri() . '/assets/js/subscription.js', array('jquery'), THEME_VERSION, true );
    wp_localize_script( 'wz-subscription', 'wz_ajax', array(
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'nonce'    => wp_create_nonce( 'wz_subscribe_nonce' )
    ) );
}
add_action( 'wp_enqueue_scripts', 'wz_enqueue_subscription_script' );

/**
 * Add comment notification when a new comment is posted.
 *
 * @param int        $comment_id The comment ID.
 * @param WP_Comment $comment    The comment object.
 */
function wz_add_comment_notification( $comment_id, $comment ) {
    if ( 1 != $comment->comment_approved ) {
        return;
    }

    $post_id = $comment->comment_post_ID;
    $post_author_id = get_post_field( 'post_author', $post_id );
    $comment_author_id = $comment->user_id;

    $notifications = [];

    // Notify post author
    if ( $post_author_id != $comment_author_id ) {
        $notifications[] = array(
            'type' => 'post_reply',
            'comment_id' => $comment_id,
            'post_id' => $post_id,
            'comment_author_id' => $comment_author_id,
            'timestamp' => time(),
            'read' => false,
        );
        add_user_meta( $post_author_id, 'wz_notifications', $notifications[count($notifications)-1], false);
    }

    // Notify parent comment author
    if ( $comment->comment_parent ) {
        $parent_comment = get_comment( $comment->comment_parent );
        $parent_comment_author_id = $parent_comment->user_id;

        if ( $parent_comment_author_id != $comment_author_id && $parent_comment_author_id != $post_author_id) {
             $notifications[] = array(
                'type' => 'comment_reply',
                'comment_id' => $comment_id,
                'post_id' => $post_id,
                'comment_author_id' => $comment_author_id,
                'timestamp' => time(),
                'read' => false,
            );
            add_user_meta( $parent_comment_author_id, 'wz_notifications', $notifications[count($notifications)-1], false);
        }
    }
}
add_action( 'wp_insert_comment', 'wz_add_comment_notification', 10, 2 );

/**
 * Register a custom post type for newsletter subscriptions.
 */
function wz_register_subscription_post_type() {
    $args = array(
        'labels'        => array(
            'name'          => __( '订阅', 'wanzicms' ),
            'singular_name' => __( '订阅', 'wanzicms' ),
            'menu_name'     => __( '邮件订阅', 'wanzicms' ),
            'all_items'     => __( '所有订阅者', 'wanzicms' ),
        ),
        'public'        => false,
        'show_ui'       => true,
        'show_in_menu'  => true,
        'menu_position' => 25,
        'menu_icon'     => 'dashicons-email-alt',
        'supports'      => array('title'),
        'capability_type' => 'post',
        'rewrite'       => false,
    );
    register_post_type( 'subscription', $args );
}
add_action( 'init', 'wz_register_subscription_post_type' );

/**
 * Handle newsletter subscription form submission via AJAX.
 */
function wz_handle_subscription() {
    check_ajax_referer( 'wz_subscribe_nonce', 'nonce' );

    $email = isset( $_POST['email'] ) ? sanitize_email( $_POST['email'] ) : '';

    if ( ! is_email( $email ) ) {
        wp_send_json_error( array( 'message' => __( '请输入一个有效的电子邮件地址。', 'wanzicms' ) ) );
        return;
    }

    $existing_subscriber = get_posts( array(
        'post_type'  => 'subscription',
        'title'      => $email,
        'post_status'=> 'publish',
        'numberposts' => 1
    ) );

    if ( ! empty( $existing_subscriber ) ) {
        wp_send_json_error( array( 'message' => __( '这个邮箱已经订阅过了！', 'wanzicms' ) ) );
        return;
    }

    $post_id = wp_insert_post( array(
        'post_title'  => $email,
        'post_type'   => 'subscription',
        'post_status' => 'publish',
    ) );

    if ( is_wp_error( $post_id ) ) {
        wp_send_json_error( array( 'message' => __( '订阅失败，请稍后再试。', 'wanzicms' ) ) );
    } else {
        wp_send_json_success( array( 'message' => __( '感谢订阅！', 'wanzicms' ) ) );
    }
}
add_action( 'wp_ajax_nopriv_wz_subscribe', 'wz_handle_subscription' );
add_action( 'wp_ajax_wz_subscribe', 'wz_handle_subscription' );

/**
 * Send an email notification to all subscribers when a new post is published.
 *
 * NOTE: For sites with a very large number of subscribers, this function could slow down
 * post publishing. A more robust solution would involve a background job queue.
 *
 * @param string  $new_status New post status.
 * @param string  $old_status Old post status.
 * @param WP_Post $post       Post object.
 */
function wz_notify_subscribers_on_new_post( $new_status, $old_status, $post ) {
    // Check if the feature is enabled in theme options
    $wanzicms_options = get_option('wanzicms_options');
    $is_enabled = isset($wanzicms_options['enable_post_notification']) ? $wanzicms_options['enable_post_notification'] : true;

    if ( ! $is_enabled ) {
        return;
    }

    // Only run for new posts published for the first time
    if ( 'publish' !== $new_status || 'publish' === $old_status ) {
        return;
    }

    // Only for 'post' post type
    if ( 'post' !== $post->post_type ) {
        return;
    }

    $subscribers_query = new WP_Query( array(
        'post_type'      => 'subscription',
        'posts_per_page' => -1,
        'post_status'    => 'publish',
        'fields'         => 'post_title',
    ) );

    if ( ! $subscribers_query->have_posts() ) {
        return;
    }
    
    $emails = $subscribers_query->posts;

    if ( empty( $emails ) ) {
        return;
    }

    $site_name = get_bloginfo( 'name' );
    $subject   = sprintf( '【%s】新文章发布：%s', $site_name, $post->post_title );

    $message = sprintf(
        '您好！<br><br>我们刚刚在【%1$s】发布了一篇新文章《%2$s》。<br><br>您可以点击以下链接查看：<br><a href="%3$s">%3$s</a><br><br>感谢您的订阅！<br>-- %1$s',
        $site_name,
        $post->post_title,
        get_permalink( $post->ID )
    );

    $headers = array(
        'Content-Type: text/html; charset=UTF-8',
        'Bcc: ' . implode( ',', $emails ), // Use Bcc to protect subscriber privacy
    );

    // Send to the admin to have a valid "To" address
    wp_mail( get_option( 'admin_email' ), $subject, $message, $headers );
}
add_action( 'transition_post_status', 'wz_notify_subscribers_on_new_post', 10, 3 );

/**
 * Enable online theme updates.
 *
 * It uses the "Plugin Update Checker" library.
 * You need to create a JSON file with update information and host it on a server.
 * The JSON file should look like this:
 * {
 *     "version": "2.0.0",
 *     "details_url": "https://example.com/theme/changelog.html",
 *     "download_url": "https://example.com/theme/wanzicms.zip"
 * }
 *
 * @see https://github.com/YahnisElsts/plugin-update-checker
 */
require get_template_directory() . '/inc/update-checker/autoload.php';
$wanzicms_update_checker = \YahnisElsts\PluginUpdateChecker\v5\PucFactory::buildUpdateChecker(
    'https://cc.guqule.com/info.json', // !!! IMPORTANT !!! URL of the theme update information file. You must change this.
    get_template_directory(),                         // Path to the theme directory.
    'wanzicms'                                        // The theme's slug.
);

